package servlet.user;

import dao.UserDao;
import entity.User;
import utils.StringHelper;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@WebServlet("/passwordchange")
public class PasswordServlet extends HttpServlet {
    UserDao ud = new UserDao();
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, IOException {
//        //从session中获取电话号码
//      String tel =(String) request.getSession().getAttribute("TEL");
        //通过电话查询到用户信息
        //User u = ud.loadBytel("tel");
        User u = ud.loadBytel("18270608096");
        System.out.println(u.toString());
        //获取到表单中的信息
        String password = request.getParameter("password");
        String password1 = request.getParameter("password1");
        String password2 = request.getParameter("password2");
        //修改密码
        //判断用户是否为空
        if(Objects.nonNull(u)){
            //判断密码是否相同
           String encodePassword = StringHelper.encrypt( password ) ;
            if(u.getPassword().equals(encodePassword)){
                //判断两次密码是否一样
                if(password1.equals(password2)){
                    u.setPassword(StringHelper.encrypt(password1));
                    boolean result = ud.updatePassword(u);
                    //判断是否修改成功
                    if(result){
                        request.setAttribute("change","密码修改成功");
                        request.getRequestDispatcher("/UserAccount/MyPassword.vm").forward(request , response );
                    }else{
                        request.setAttribute("change","密码修改失败");
                        request.getRequestDispatcher("/UserAccount/MyPassword.vm").forward(request , response );
                    }
                }else{
                    request.setAttribute("change","两次密码不一样");
                    request.getRequestDispatcher("/UserAccount/MyPassword.vm").forward(request , response );
                }
            }else{
                request.setAttribute("change","密码输入错误");
                request.getRequestDispatcher("/UserAccount/MyPassword.vm").forward(request , response );
            }
        }


    }
}
